import requests
from lxml import etree

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}
"""
登录需要的入参
    __VIEWSTATE: BvoMzHqt76SfsXIo8Bw1t5Ua2x8QozuERp4VlrLH4L8PYz7nv5kFGI5jj9R7EXOUDrIrGBADyrBHJWAVmUcQGMeODsMrQpNN5D0+t5GgAZ/5zqRDhgYtc5Is8mX/7N/6WAlDJL1jgPjm9+AmUG+tbfvCiKI=
__VIEWSTATEGENERATOR: C93BE1AE
from: http://so.gushiwen.cn/user/collect.aspx
email: 2686373675@qq.com
pwd: rfderg
code: 7gck
denglu: 登录
"""

# 首先获取__VIEWSTATE和__VIEWSTATEGENERATOR
url = 'https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx'
get_response = requests.get(url, headers=headers)
get_content = get_response.text

tree = etree.HTML(get_content)
__VIEWSTATE = tree.xpath('//input[@id="__VIEWSTATE"]/@value')[0]
__VIEWSTATEGENERATOR = tree.xpath('//input[@id="__VIEWSTATEGENERATOR"]/@value')[0]

code = tree.xpath('//img[@id="imgCode"]/@src')[0]
code_url = 'https://so.gushiwen.cn' + code

# 这里需要注意因为每次请求接口返回的验证码是不一样的，所以我们不能使用urllib的方式下载到本地，
# 需要用requests的seccion方法  通过session返回的值就能变成一个对象
session = requests.session()
sess_response = session.get(code_url)

# 拿到图片的二进制数据下载图片到本地
code_content = sess_response.content

# wb模式是写入二进制数据
with open('code.png', 'wb') as fp:
    fp.write(code_content)

code_name = input('请输入验证码：')

# 现在就能登录啦
# 但是我们必须要使用刚生成的 session去掉接口才能保证和验证码下载的时候调用的是一个接口，这样验证码才有效
login_url = 'https://so.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fso.gushiwen.cn%2fuser%2fcollect.aspx'

login_data = {
    "__VIEWSTATE": __VIEWSTATE,
    "__VIEWSTATEGENERATOR": __VIEWSTATEGENERATOR,
    "from": "http://so.gushiwen.cn/user/collect.aspx",
    "email": "595165358@qq.com",
    "pwd": "action",
    "code": code_name,
    "denglu": "登录"
}

login_response = session.post(url=login_url, data=login_data, headers=headers)

login_content = login_response.text

with open('gushiwen.html', 'w', encoding='utf-8') as fp:
    fp.write(login_content)
